import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter_hx/base/utils/object_warp.dart';
import 'package:flutter_hx/base/utils/preference_utils.dart';
import 'package:flutter_hx/model/user_info.dart';
import 'package:flutter_hx/network/HttpGo.dart';
import 'package:get/get.dart';
const _tokenCacheKey="token";
const _userInfoKey="userInfo";
class UserService extends GetxService{
  static UserService get to => Get.find();
  var _token="";
  final user=Rx<UserInfo?>(null);
  final isLogin=false.obs;



  String get token=>_token;

  set userInfo(UserInfo userInfo){
    user.value=userInfo;
  }

  Future refreshUser()async{
    final res=await HttpGo.instance.get("/member/info");
    res.ifSuccess((data)async{
      user.value=UserInfo.fromJson(data);
      await PreferenceUtils.instance.saveString(_userInfoKey, jsonEncode(data));
    });
  }


  Future login(String token)async{
    _token=token;
    await PreferenceUtils.instance.saveString(_tokenCacheKey, _token);
    await refreshUser();
    isLogin.value=true;
  }

  Future logOut()async{
    _token="";
    isLogin.value=false;
  }

  @override
  void onInit() async{
    printInfo(info: "onInit");
    await PreferenceUtils.instance.initSharedPreferences();
    final token= PreferenceUtils.instance.getString(_tokenCacheKey);
    _token=token;
    isLogin.value=_token.isNotEmpty;
    super.onInit();
    if(isLogin.value){
      final userCache=PreferenceUtils.instance.getString(_userInfoKey);
      if(userCache.isNotEmpty){
        user.value=UserInfo.fromJson(json.decode(userCache));
      }
      refreshUser();
    }
  }
}